package com.testmanager.testmananger.foundation.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;

public class JWTUtil {

    public static final long EXPIRE_TIME = 24*3600*1000;  //有效时间

    private static final String TOKEN_SECRET = "shuiyouTokenSecretKey";


    /**
     * 生成签名 1天后过期
     * @param userName
     * @param userId
     * @return
     */
    public static String sign (String name,String userName,long userId){

        Date date = new Date(System.currentTimeMillis()+ EXPIRE_TIME) ; // 有效时间

        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); //私钥及加密算法

        HashMap<String ,Object>  header = new HashMap<>(2);
        header.put("typ","JWT");
        header.put("alg","HS256");

        return JWT.create().withHeader(header).withClaim("username",userName)
                .withClaim("id",userId)
                .withClaim("name",name)
                .withExpiresAt(date).sign(algorithm);


    }


    public static boolean verity(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);

            return true;
        } catch (IllegalArgumentException e) {
            return false;
        } catch (JWTVerificationException e) {
            return false;
        }catch (NullPointerException e){
            return false;
        }

    }

    @SuppressWarnings(value = "")
    public static long getUserid(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);

            return jwt.getClaims().get("userId").asLong();
        } catch (IllegalArgumentException e) {
            return 0;
        } catch (JWTVerificationException e) {
            return 0 ;
        }

    }

    public static String getName(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);

            return jwt.getClaims().get("name").asString();
        } catch (IllegalArgumentException e) {
            return "adminerror";
        } catch (JWTVerificationException e) {
            return "adminerror" ;
        }

    }



}
